package org.morningangel.servlet.android;

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;

import javax.servlet.annotation.MultipartConfig;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.Part;

import org.morningangel.bean.UserImg;
import org.morningangel.dao.UserImgDao;
import org.morningangel.dao.impl.UserImgDaoImpl;

@WebServlet(name = "UploadFileServlet", urlPatterns = "/android/upload")
@MultipartConfig
// 标识Servlet支持文件上传
public class UploadFileServlet extends HttpServlet {
	private static final long serialVersionUID = -4920348972533363728L;

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		Integer userId = Integer.parseInt(request.getParameter("userId"));
		Integer activityId = Integer.parseInt(request.getParameter("activityId"));
		//String filePath = request.getParameter("filePath");
		System.out.println("userId:" + userId);
		System.out.println("activityId:" + activityId);
		//System.out.println("filePath:" + filePath);
		// 存储路径
		String storePath = request.getServletContext().getRealPath(
				"/uploadFile/" + userId + "/");
		File path = new File(storePath);
		if (!path.exists()) {
			path.mkdirs();
		}
		Part part = request.getPart("file");
		// Servlet3没有提供直接获取文件名的方法,需要从请求头中解析出来
		// 获取请求头
		String header = part.getHeader("content-disposition");
		// 获取文件名
		String fileName = parseFileName(header);
		
		System.out.println("fileName:" + fileName);
		fileName = new Date().getTime() + fileName.substring(fileName
				.lastIndexOf("."));
		System.out.println("fileName:" + fileName);
		// 把文件写到指定路径
		part.write(storePath + File.separator + fileName);
		PrintWriter out = response.getWriter();
		UserImgDao userImgDao = new UserImgDaoImpl();
		UserImg userImg = new UserImg();
		userImg.setActivityId(activityId);
		userImg.setImgAddr("uploadFile/" + userId + "/" + fileName);
		userImg.setUserId(userId);
		userImg.setTime(new Date());
		userImgDao.save(userImg);
		out.print("{\"isSuccess\":\"1\"}");
		out.flush();
		out.close();
	}

	/**
	 * 
	 * 根据请求头解析出文件名
	 * 
	 * 请求头的格式：form-data; name="file"; filename="a.txt"
	 * 
	 * @param header
	 * 
	 * @return
	 */
	public String parseFileName(String header) {
		return header.substring(header.lastIndexOf("=") + 2,
				header.length() - 1);
	}

}